package com.cola.colaboot.module.design.controller;

import com.cola.colaboot.config.dto.Res;
import com.cola.colaboot.config.security.SecurityUtils;
import com.cola.colaboot.module.design.pojo.DesignImgGroup;
import com.cola.colaboot.module.design.pojo.DesignImgPool;
import com.cola.colaboot.module.design.service.DesignImgPoolService;
import com.cola.colaboot.module.system.controller.SysFileController;
import com.cola.colaboot.module.system.pojo.SysFile;
import com.cola.colaboot.module.system.pojo.SysUser;
import com.cola.colaboot.module.system.service.SysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;

@RestController
@RequestMapping("/imgPool")
public class DesignImgPoolController {

    @Autowired
    private DesignImgPoolService poolService;

    @Autowired
    private SysFileService fileService;

    @GetMapping("/pageList")
    public Res<?> queryPageList(DesignImgPool pool,
                @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
        return Res.ok(poolService.pageList(pool,pageNo,pageSize));
    }

    @PostMapping("/saveOrUpdate")
    public Res<?> saveOrUpdate(@RequestBody DesignImgPool pool){
        SysUser sysUser = SecurityUtils.currentUser();
        pool.setCreateUser(sysUser.getId());
        poolService.saveOrUpdate(pool);
        return Res.ok("保存成功");
    }

    @DeleteMapping("/delete/{id}")
    public Res<?> delete(@PathVariable String id){
        DesignImgPool imgPool = poolService.getById(id);
        SysFile sysFile = fileService.getById(imgPool.getFileId());
        try{
            File file = new File(SysFileController.FILE_ROOT_URL + sysFile.getFileUrl());
            file.delete();
        }catch (Exception e){
            e.printStackTrace();
        }
        poolService.removeById(id);
        fileService.removeById(imgPool.getFileId());
        return Res.ok("删除成功");
    }
}
